package com.pig4cloud.pig.module.controller.terminal;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.pig4cloud.pig.common.core.util.QRCodeUtilEx;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.log.annotation.SysLog;
import com.pig4cloud.pig.common.mybatis.page.PageUtils;
import com.pig4cloud.pig.common.mybatis.page.TableDataInfo;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import com.pig4cloud.pig.module.api.entity.estate.Estate;
import com.pig4cloud.pig.module.api.entity.terminals.Terminals;
import com.pig4cloud.pig.module.service.estate.IEstateService;
import com.pig4cloud.pig.module.service.terminals.ITerminalsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 巡检设备Controller
 *
 * @author ruoyi
 * @date 2022-04-29
 */
@Validated
@Api(value = "巡检设备控制器", tags = {"巡检设备管理"})
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/terminals")
public class TerminalsController {

    private final ITerminalsService terminalsService;
	private final IEstateService estateService;

	@Value("${ruoyi.profile}")
	private String uploadPath;

//	@Value("${ruoyi.imgUrl}")
//	private String imgUrl;

	@Value("${ruoyi.imgUrlOss}")
	private String imgUrlOss;

    /**
     * 查询巡检设备列表
     */
    @ApiOperation("查询巡检设备列表")
    @PreAuthorize("@pms.hasPermission('module:terminals:list')")
    @GetMapping("/list")
    public TableDataInfo<Terminals> list(@Validated Terminals terminals) {
        QueryWrapper<Terminals> qw = new QueryWrapper<>();
		PigUser sysUser = SecurityUtils.getUser();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		}if(sysUser.getUserType() == 3){
			qw.eq("estate_id",terminals.getEstateId());
		}else{
			if(terminals.getEstateId()!=null){
				qw.eq("estate_id",terminals.getEstateId());
			}
		}

        if(StrUtil.isNotEmpty(terminals.getTerminalName())){
			qw.like("terminal_name",terminals.getTerminalName());
		}

        TableDataInfo<Terminals> td = PageUtils.buildDataInfo(terminalsService.page(PageUtils.buildPage(),qw));
        List<Terminals> list = td.getData();
        for (Terminals terminals1 : list){
			Estate estate = estateService.findById(terminals1.getEstateId());
			if(estate!=null){
				terminals1.setEstateName(estate.getEstateName());
			}
			if(StrUtil.isNotEmpty(terminals1.getQrCode())){
				terminals1.setQrCode(imgUrlOss + terminals1.getQrCode());
			}
		}
        return td;
    }

    /**
     * 导出巡检设备列表
     */
    @ApiOperation("导出巡检设备列表")
    @PreAuthorize("@pms.hasPermission('module:terminals:export')")
    @SysLog("巡检设备")
    @GetMapping("/export")
    public List export(@Validated Terminals terminals) {
		QueryWrapper<Terminals> qw = new QueryWrapper<>();
		PigUser sysUser = SecurityUtils.getUser();
		if(sysUser.getUserType() == 2){//物业公司
			qw.eq("property_id",sysUser.getPropertyId());
		}if(sysUser.getUserType() == 3){
			qw.eq("estate_id",terminals.getEstateId());
		}else{
			if(terminals.getEstateId()!=null){
				qw.eq("estate_id",terminals.getEstateId());
			}
		}
        List<Terminals> list = terminalsService.list(qw);
        // ExcelUtil<Terminals> util = new // ExcelUtil<Terminals>(Terminals.class);
        return  list;// util.exportExcel(list, "巡检设备");
    }

    /**
     * 获取巡检设备详细信息
     */
    @ApiOperation("获取巡检设备详细信息")
    @PreAuthorize("@pms.hasPermission('module:terminals:query')")
    @GetMapping("/{id}")
    public R<Terminals> getInfo(@NotNull(message = "主键不能为空") @PathVariable("id") Long id) {
        Terminals terminals = terminalsService.getById(id);
        return R.ok(terminals);
    }

    /**
     * 新增巡检设备
     */
    @ApiOperation("新增巡检设备")
    @PreAuthorize("@pms.hasPermission('module:terminals:add')")
    @SysLog("巡检设备")

    @PostMapping()
    public R<Void> add(@Valid @RequestBody Terminals terminals) {
		Date date = new Date();
    	if(terminals == null){
			terminals = new Terminals();
		}
		terminals.setCreateTime(new Date());
		try{
			String terminalNum = "T" + date.getTime() / 1000;
			terminals.setTerminalNum(terminalNum);
			String qrCode = "";
			String fileName = "terminal_qr_" + terminals.getTerminalNum() + ".jpg";
			String content = "https://www.sdyuedou.com/wxmini/terminal/qr?num=" + terminals.getTerminalNum();
			int upload_type = 0;//FileUploadUtils.TYPE_TERMINALS;
			System.out.println("content:  "+ content);
			String img_key = ""; // FileUploadUtils.getUploadPrefix(upload_type) + fileName;
			QRCodeUtilEx.createQrCodeImg(content, "编号：" + terminals.getTerminalNum(),
				null, uploadPath +"/"+img_key, true, fileName, upload_type);
			qrCode = img_key;
			terminals.setQrCode(qrCode);
		}catch (Exception ex){
			ex.printStackTrace();
		}
        return R.okByRow(terminalsService.save(terminals) ? 1 : 0);
    }

	/**
	 * 重置二维码
	 */
	@SysLog("重置二维码")
	@PostMapping("/resetQrCode")
	@ResponseBody
	@PreAuthorize("@pms.hasPermission('module:terminals:edit')")
	public R<Void> resetQrCode(@RequestBody Terminals terminals) {
		if(terminals.getId()!=null){
			try{
				terminals = terminalsService.getById(terminals.getId());
				if(terminals!=null){
					String qrCode = "";
					String fileName = "terminal_qr_" + terminals.getTerminalNum() + ".jpg";
					String content = "https://www.sdyuedou.com/wxmini/terminal/qr?num=" + terminals.getTerminalNum();
					int upload_type = 0;//FileUploadUtils.TYPE_TERMINALS;
					System.out.println("content:  "+ content);
					String img_key = "";// FileUploadUtils.getUploadPrefix(upload_type) + fileName;
					QRCodeUtilEx.createQrCodeImg(content, "编号：" + terminals.getTerminalNum(),
						null, uploadPath +"/"+img_key, true, fileName, upload_type);
					qrCode = img_key;
					terminals.setQrCode(qrCode);
				}
			}catch (Exception ex){
				ex.printStackTrace();
			}
			if (terminalsService.updateById(terminals)) {
				return R.ok();
			}
		}
		return R.failed();
	}

    /**
     * 修改巡检设备
     */
    @ApiOperation("修改巡检设备")
    @PreAuthorize("@pms.hasPermission('module:terminals:edit')")
    @SysLog("巡检设备")

    @PutMapping()
    public R<Void> edit(@Valid @RequestBody Terminals terminals) {
    	if(StrUtil.isEmpty(terminals.getTerminalNum())){
			Date date = new Date();
			String terminalNum = "T" + date.getTime() / 1000;
			terminals.setTerminalNum(terminalNum);
		}
        return R.okByRow(terminalsService.updateById(terminals) ? 1 : 0);
    }

    /**
     * 删除巡检设备
     */
    @ApiOperation("删除巡检设备")
    @PreAuthorize("@pms.hasPermission('module:terminals:remove')")
    @SysLog("巡检设备")
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")  @PathVariable Long[] ids) {
        return R.okByRow(terminalsService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
    }
}
